'''
Created on Oct 19, 2009

@author: mkiyer
'''
import sys
import operator

__knowngene_path = '/lab/mkiyer/refdb/ucsc_tables/knownGene.txt'

def parse_ucsc_genes(fhd):
    '''
    name varchar(255) NOT NULL default '',
    chrom varchar(255) NOT NULL default '',
    strand char(1) NOT NULL default '',
    txStart int(10) unsigned NOT NULL default '0',
    txEnd int(10) unsigned NOT NULL default '0',
    cdsStart int(10) unsigned NOT NULL default '0',
    cdsEnd int(10) unsigned NOT NULL default '0',
    exonCount int(10) unsigned NOT NULL default '0',
    exonStarts longblob NOT NULL,
    exonEnds longblob NOT NULL,
    proteinID varchar(40) NOT NULL default '',
    alignID varchar(255) NOT NULL default '',
    '''
    for line in fhd:
        line = line.strip()
        if line is None:
            continue
        if line.startswith('#'):
            continue
        fields = line.strip().split('\t')
        g = type('Gene', (object,), dict())
        g.name = fields[0]
        g.chrom = fields[1]
        g.strand = fields[2]
        g.txstart = int(fields[3])
        g.txend = int(fields[4])
        g.cdsstart = int(fields[5])
        g.cdsend = int(fields[6])
        g.exon_count = int(fields[7])
        g.exon_starts = map(int, fields[8].split(',')[:-1])
        g.exon_ends = map(int, fields[9].split(',')[:-1])
        g.exons = zip(g.exon_starts, g.exon_ends)
        g.introns = zip(g.exon_ends, g.exon_starts[1:])
        yield g


def print_raw_junction(chrom, start, end, strand):
    sys.stdout.write('\t'.join([chrom,
                                str(start),
                                str(end),
                                strand]))
    sys.stdout.write('\n')

if __name__ == '__main__':
    junctions = set([])
    for g in parse_ucsc_genes(open(__knowngene_path)):
        for jstart, jend in g.introns:
            junctions.add((g.chrom, jstart-1, jend, g.strand))
    for j in sorted(junctions):
        print_raw_junction(*j)
